package servidor;

import common.RemotInterface;
import common.TDSLanguageUtils;
import java.net.URL;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.util.Properties;
import javax.swing.JOptionPane;
import servidor.impl.RemotImpl;

/**
 * Classe Servidor
 * @author Juan Luís Chávez Lobato i Jesús Hernàndez Garcia
 */

public class Servidor extends javax.swing.JFrame {

    private RemotInterface rmiServidor;
    
    /**
     * Creates new form Servidor
     */
    public Servidor() {
        initComponents();
        setTitle(TDSLanguageUtils.getMessage("titol.finestra"));
        BotoIniciar.setText(TDSLanguageUtils.getMessage("boto.iniciar"));
        BotoAturar.setText(TDSLanguageUtils.getMessage("boto.parar"));
        TexteEstat.setText(TDSLanguageUtils.getMessage("missatge.noiniciat"));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        BotoIniciar = new javax.swing.JButton();
        BotoAturar = new javax.swing.JButton();
        TexteEstat = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        BotoIniciar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        BotoIniciar.setText("Iniciar Servidor");
        BotoIniciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotoIniciarActionPerformed(evt);
            }
        });

        BotoAturar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        BotoAturar.setText("Aturar Servidor");
        BotoAturar.setEnabled(false);
        BotoAturar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotoAturarActionPerformed(evt);
            }
        });

        TexteEstat.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        TexteEstat.setText("El servidor està aturat");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(BotoIniciar, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(BotoAturar, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(TexteEstat)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(TexteEstat)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(BotoIniciar, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
                    .addComponent(BotoAturar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BotoIniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotoIniciarActionPerformed
        try {
            
            if ( rmiServidor == null ) {
                rmiServidor = new RemotImpl();
                
                Properties prop = new Properties();
                URL url = ClassLoader.getSystemResource("properties/configuration.properties");
                prop.load(url.openStream());      
                
                String pathRMI = prop.getProperty("pathrmi");
                Naming.rebind(pathRMI, rmiServidor);
            }

            
            TexteEstat.setText(TDSLanguageUtils.getMessage("missatge.iniciat"));
            BotoIniciar.setEnabled(false);
            BotoAturar.setEnabled(true);
            
        } catch (RemoteException e) {
            JOptionPane.showMessageDialog 
                    (null, TDSLanguageUtils.getMessage("ERR_REG_RMI"), "Error", JOptionPane.ERROR_MESSAGE);
        } catch (Exception e) {
            JOptionPane.showMessageDialog     
                    (null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_BotoIniciarActionPerformed

    /*
     * Para el servidor i tanca la finestra
     */
    private void BotoAturarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotoAturarActionPerformed
        dispose();
        System.exit(0);
    }//GEN-LAST:event_BotoAturarActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        dispose();
        System.exit(0);
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Servidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Servidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Servidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Servidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                TDSLanguageUtils.setDefaultLanguage("i18n/messages");
                new Servidor().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BotoAturar;
    private javax.swing.JButton BotoIniciar;
    private javax.swing.JLabel TexteEstat;
    // End of variables declaration//GEN-END:variables
}
